<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>16 倒计时效果</title>

  <style>
    .countdown {
      font-size: 2rem;
    }
  </style>
</head>

<body>
  <h1>需要基于HTTP协议打开才能进行 ajax请求</h1>

  <div class="countdown">距离秒杀还有 01:39:22</div>


  <script>
    let countdown = document.querySelector(".countdown");
    let target = new Date("2020/11/04 23:22:00"),
      now = new Date(),
      timer = null;

    function queryServerDate(callback) {
      let xhr = new XMLHttpRequest();
      xhr.open("GET", 'http://baiud.com');
      xhr.onreadystatechange = function () {
        if (xhr.status === 200 && xhr.readyState === 2) {
          // GMT 格林威治时间 (需要转换为标准的北京时间格式 => new Date()放进来转换一下)
          let time = xhr.getResponseHeader('Date');
          callback && callback(new Date(time));
        }
      }
      xhr.send(null);
    }

    function computed() {
      let diffTime = target - now;
      if (diffTime <= 0) {
        // 到达抢购时间
        clearInterval(timer);
        countdown.innerHTML = `开枪把！`;
        return;
      }
      // 没到达抢购时间
      let hours = Math.floor(diffTime / (60 * 60 * 1000));
      diffTime = diffTime - hours * 60 * 60 * 1000;
      let minutes = Math.floor(diffTime / (60 * 1000))
      diffTime = diffTime - minutes * 60 * 1000;
      let seconds = Math.floor(diffTime / 1000);

      hours < 10 ? hours = `0${hours}` : null;
      minutes < 10 ? minutes = `0${minutes}` : null;
      seconds < 10 ? seconds = `0${seconds}` : null;

      countdown.innerHTML = `距离秒杀还有 ${hours}:${minutes}:${seconds}`;
    }

    queryServerDate(time => {
      // 获取到服务器返回的时间
      now = time;

      // 计算时间差
      computed();

      // 每隔一秒钟，在现有的时间上加去一秒钟
      timer = setInterval(_ => {
        now = +now + 1000;
        // console.log(now);
        computed();
      }, 1000)

    });
  </script>
</body>

</html>